﻿using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using Internal.KuiHuaBaoDian.Services.Guide;
using UnityEngine;

namespace KuiHuaBaoDian.Services.Guide {

    [NodeTitle("按索引或名称找到对象")]
    public sealed class GuideQuery_ByIndexOrName : GuideStepProcess, IGuideQueryInternal {

        [SerializeField, Label("勾选按索引，否则按名称")]
        private bool m_IndexOrName;

        [SerializeField, Label("值")]
        private string m_Value;

        IReadOnlyList<GuideReference> IGuideQueryInternal.ReferenceList => m_ReferenceList;
        private List<GuideReference> m_ReferenceList;

        protected override void Dispose() {
            m_ReferenceList = null;
        }

        protected override UniTask Execute() {
            m_ReferenceList = new List<GuideReference>();
            var reference = ReferenceList[0];
            if (reference.Target is GameObject gameObject && !string.IsNullOrWhiteSpace(m_Value)) {
                Transform transform = null;
                if (m_IndexOrName) {
                    var index = int.Parse(m_Value);
                    if (index >= 0 && gameObject.transform.childCount > index) {
                        transform = gameObject.transform.GetChild(index);
                    }
                } else {
                    transform = gameObject.transform.Find(m_Value);
                }
                if (transform != null) {
                    m_ReferenceList.Add(new GuideReference { Target = transform.gameObject });
                }
            }
            return UniTask.CompletedTask;
        }
    }
}
